import React, { useCallback, useEffect, useState } from 'react'
import { connect  } from 'react-redux'
import './index.less'
import { Checkbox, message, Spin  } from 'antd'
import { menuListApi, userInfoApi, userLoginApi } from '../../Apis/userApi'
import { menuListAct, tokenAct, userInfoAct } from '../../store/actions/commonAct'
import { AES, MD5 } from 'crypto-js'
import { enc } from 'crypto-js/core'

function Login( {dispatch, history } ) {

    // 定义数据
    const [loginObj, setLoginObj] = useState({id: '', password: ''}) // 登录数据
    const [remember, setRemember] = useState(false) // 记住密码
    const [loading, setLoading] = useState(false) // 加载提示

    // 记住密码功能初始化
    useEffect(function() {
        // 取出加密后的信息并解密赋值给loginObj,并将记住密码勾选
        let myloginInfo = localStorage.getItem('login-info')
        if(!!myloginInfo) {
            try {
                myloginInfo = AES.decrypt(myloginInfo, 'yibaiyun').toString(enc.Utf8)
                myloginInfo = JSON.parse(myloginInfo)
                setLoginObj({...loginObj, id: myloginInfo.id, password: myloginInfo.password})
                setRemember(true)
            } catch{

            }
        }
    }, [])
    
    // 登录功能
    const loginEvt = useCallback(function() {
        // 调用接口打开加载
        setLoading(true)
        userLoginApi({
            id: loginObj.id,
            password: MD5(loginObj.password).toString()
        }).then(result => {
            
            if(loginObj.id === '' || loginObj.password === '') {
                message.error('用户名密码不能为空')
                return
            }

            if(result.code !== 200) {
                message.error('登录失败，请重试！')
                // 接口返回，关闭加载
                setTimeout(function() {
                    setLoading(false)
                })
                return
            }
             
            // 加密缓存密码
            if(remember) {
                let AesLoginObj = AES.encrypt(JSON.stringify(loginObj), 'yibaiyun').toString()
                localStorage.setItem('login-info', AesLoginObj)
            }else {
                localStorage.removeItem('login-info')
            }

            // 缓存用户信息
            userInfoApi({id:loginObj.id}).then(function(data) {
                // console.log(data)
                dispatch(userInfoAct(data.data))
            })

            // 缓存首页菜单
            menuListApi().then(function(list) {
                // console.log(list)
                dispatch(menuListAct(list.data))
            })

            // 缓存token
            dispatch(tokenAct(result.data.token))

            // 接口返回，关闭加载
            setTimeout(function() {
                setLoading(false)
            })

            history.push('./home')
            
        })
    }, [remember, loginObj])
   
    
    return (
        <div className='login-container'>
            {/* 背景 */}
            <div className='backImg'>
                <img className='backImgOne' style={{width:'100%', height:'100%'}}  src={require('../../image/login-bg.png')}/>
            </div>
            {/* 登录输入框-【 */}
            <div className='loginBox'>
                <Spin size='middle' tip="Loading..." spinning={loading}>
                    <div className='title'>易佰云</div>
                    <div className='text'>—————<span>贸易管理系统</span>—————</div>
                    <input size='middle' value={loginObj.id} onChange={
                        function(e) {
                            setLoginObj({...loginObj, id: e.target.value})
                        }
                    } placeholder='请输入用户名'/>
                    <input size='middle'  value={loginObj.password} onChange={
                        function(e) {
                            setLoginObj({...loginObj, password: e.target.value})
                        }
                    } placeholder='请输入密码'/>
                    <div className='check'>
                        <Checkbox checked={remember}  onChange={function(e) {
                            setRemember(e.target.checked)
                        }}>记住密码?</Checkbox>
                    </div>
                    <button onClick={loginEvt}>
                        登录
                    </button>
                </Spin>
            </div>
        </div>
    )
}
function mapStateToProps(state) {
    return {
        token:state.common.token,
        userInfo:state.common.userInfo
    }
}
export default connect(mapStateToProps)(Login)